/**
 * Created by shitao on 15/10/17.
 */
(function () {

    // 创建angular工厂对象
    angular.module('my-tabs.apis')
        .factory('friendApi', friendApi);
    // 申明依赖
    friendApi.$inject = ['api', '$http', '$q', '_'];

    /**
     * 用户接口。
     *
     * @param api 对象，数据接口URL
     * @returns 对象，用户接口
     */
    function friendApi(api, $http, $q, _) {

        var friendApi = {
            getFriends: getFriends,
            getDialog: getDialog
        };

        var words = [];

        /**
         * 根据用户Id获取该用户应用列表。
         *
         * @param userId 字符串，用户Id
         */
        function getFriends() {
            return $http.get(api.FRIENDS);
        };


        function getDialog(friend, me) {
            var defer = $q.defer(),
                dialog;
            if (_.isEmpty(words)) {
                $http.get(api.WORDS)
                    .then(function (data) {
                        words.length = 0;
                        _.each(data.data, function (item) {
                            words.push(item);
                        })
                        dialog = mockDialog(friend, me);
                        defer.resolve(dialog);
                    }, function () {
                        defer.reject('数据获取失败');
                    });
            } else {
                dialog = mockDialog(friend, me);
                defer.resolve(dialog);
            }
            return defer.promise;
        };

        function mockDialog(friend, me) {
            var len = words.length,
                s = _.random(len / 5, len * 2 / 3),
                i, selected = {}, word, dialog = [],
                owner, item;
            while (s > 0) {
                i = _.random(0, len - 1);
                if (!selected.hasOwnProperty(i)) {
                    selected[i] = true;
                    word = words[i];
                    if (_.random(0, 10) > 5) {
                        owner = friend;
                    } else {
                        owner = me;
                    }
                    item = {
                        word: word,
                        owner: owner
                    };
                    dialog.push(item);
                    s--;
                }
            }
            return dialog;
        };

        return friendApi;
    };
})();
